require(["./config"],function(){
  require(["jquery","template","loadHF","cookie"],function($,template){
    function Cart(){
      $.cookie.json = true

      this.cart = [];
      this.loadCart();
      this.addListener();
      this.amount();
    }
    Cart.prototype = {
      constructor: Cart,
      loadCart(){
        const cart = this.cart = $.cookie("cart") || [];
        const data= {cart};
        const html = template("cart-template",data);
        $(".left_b").html(html)
      },
      addListener(){
        $(".left_b").on("click",".del",this.delProductHandler.bind(this))
        $(".amount").on("click", "li", this.modifyAmountHandler.bind(this))
        $("input.chk_all").on("click", this.checkAllHandler.bind(this))
        $("input.chk_prod").on("click", this.checkProdHandler.bind(this))
      },
      //删除行
      delProductHandler(event){
        const $p = $(event.target).parents(".left_body");
        const id = $p.data("id")
        this.cart = this.cart.filter(curr =>curr.id != id)
        $.cookie("cart",this.cart,{expires:7,path:"/"})
        $p.remove();
      },
      //自定义下拉菜单
      amount(event) {
        $(".moth").click(function(event){
        event.stopPropagation
				? event.stopPropagation()
        : event.cancelBubble = true;
        const src = event.target;
        $(src).find(".amount").css({display:"block"})
        });
        $(".amount").on("click",function(e){
          e.stopPropagation
          ? e.stopPropagation()
          : e.cancelBubble = true;
          var src = e.target;
          console.log(src)
          $(src).parent().siblings(".m").html($(src).html())
          $(".amount").css({display:"none"})
        })
        document.onclick = function() {
          $(".amount").css({display:"none"})
        }
      },
      //获取下拉菜单的值存cookie
      modifyAmountHandler(event) {
        const $p = $(event.target).parents(".left_body");
        const id = $p.data("id")
				const prod = this.cart.find(curr => curr.id == id)
        const txt = $(event.target).html();
        console.log($(event.target).html())
        prod.amount = Number(txt)
				$.cookie("cart", this.cart, {expires: 7, path: "/"})
				$p.find(".m").val(prod.amount)
				$p.find(".lb_6").text((prod.price*prod.amount).toFixed(2))
      },
      checkAllHandler(event) {
				const ch = $(event.target).prop("checked")
				$("input.chk_prod").prop("checked", ch)
				this.calcTotalPrice()
      },
      checkProdHandler() {
				$("input.chk_all").prop("checked", $("input.chk_prod:checked").length === this.cart.length)
				this.calcTotalPrice()
      },
      calcTotalPrice() {
				let sum = 0;
				console.log($("input.chk_prod:checked"))
				$("input.chk_prod:checked").each((index, element) => {
					sum += Number($(element).parents(".left_body").find(".lb_6").text())
				})
				Number($(".total").text(sum)).toFixed(2)
			}
    }

    new Cart()
  })
});
